import React, { useState } from "react";
import { styled } from "@mui/material/styles";
import {
  Divider,
  Grid,
  List,
  ListItem,
  ListItemIcon,
  ListItemText,
  Paper,
  TextField,
  Typography,
} from "@mui/material";
import PersonIcon from "@mui/icons-material/Person";
import DomainIcon from "@mui/icons-material/Domain";
import Avatar from "@mui/material/Avatar";
import "./UserPage.css";
import ClassIcon from "@mui/icons-material/Class";
import ImportContactsIcon from "@mui/icons-material/ImportContacts";
import SchoolIcon from "@mui/icons-material/School";
import IMG from "../../../img/tmp/cover.jpg";
import { useEffect } from "react";
import { useContext } from "react";
import { TitleContext } from "../../../router";
import EmailIcon from "@mui/icons-material/Email";
import { UserProContext } from "../../../App";
import { Box } from "@mui/system";
import { useQuery } from "@tanstack/react-query";
import { COMMENT_URL, GETTAGS_URL } from "../../../constants/url";
import { getQueryFn } from "../../../query/getQueryFn";
import Loading from "../../../components/loading";
import { queryClient } from "../../../query/CustomQueryClient";
import { useNavigate } from "react-router-dom";
import { GET_EXAM_URL } from "../../../constants/url";
import Button from "@mui/material/Button";
import { GET_COURSEAPPLICATION_URL } from "../../../constants/url";
import { mutateQueryFn } from "../../../query/mutateQueryFn";
import { useMutation } from "@tanstack/react-query";
import PlaylistAddCheckIcon from "@mui/icons-material/PlaylistAddCheck";
import PlaylistAddCheckRoundedIcon from "@mui/icons-material/PlaylistAddCheckRounded";
import FormatListBulletedIcon from "@mui/icons-material/FormatListBulleted";
import DoneIcon from "@mui/icons-material/Done";

const Item = styled(Paper)(({ theme }) => ({
  backgroundColor: theme.palette.mode === "dark" ? "#1A2027" : "#fff",
  ...theme.typography.body2,
  padding: theme.spacing(1),
  textAlign: "center",
  color: theme.palette.text.secondary,
}));

const title2 = {
  name: "title2",
  keyCommand: "title2",
  button: { "aria-label": "Add title text" },
  icon: (
    <svg width="12" height="12" viewBox="0 0 512 512">
      <path
        fill="currentColor"
        d="M496 80V48c0-8.837-7.163-16-16-16H320c-8.837 0-16 7.163-16 16v32c0 8.837 7.163 16 16 16h37.621v128H154.379V96H192c8.837 0 16-7.163 16-16V48c0-8.837-7.163-16-16-16H32c-8.837 0-16 7.163-16 16v32c0 8.837 7.163 16 16 16h37.275v320H32c-8.837 0-16 7.163-16 16v32c0 8.837 7.163 16 16 16h160c8.837 0 16-7.163 16-16v-32c0-8.837-7.163-16-16-16h-37.621V288H357.62v128H320c-8.837 0-16 7.163-16 16v32c0 8.837 7.163 16 16 16h160c8.837 0 16-7.163 16-16v-32c0-8.837-7.163-16-16-16h-37.275V96H480c8.837 0 16-7.163 16-16z"
      />
    </svg>
  ),
  execute: ({ state, view }) => {
    if (!state || !view) return;

    const lineInfo = view.state.doc.lineAt(view.state.selection.main.from);
    let mark = "#";

    const matchMark = lineInfo.text.match(/^#+/);

    if (matchMark && matchMark[0]) {
      const txt = matchMark[0];
      if (txt.length < 6) {
        mark = txt + "#";
      }
    }

    if (mark.length > 6) {
      mark = "#";
    }
    const title = lineInfo.text.replace(/^#+/, "");
    view.dispatch({
      changes: {
        from: lineInfo.from,
        to: lineInfo.to,
        insert: `${mark}${title}`,
      },
      // selection: EditorSelection.range(lineInfo.from + mark.length, lineInfo.to),
      selection: { anchor: lineInfo.from + mark.length },
    });
  },
};

export default function UserPage() {
  const [markdown, setMarkdown] = useState();
  const userproContext = useContext(UserProContext);
  const [name, setName] = useState();
  const titleContext = useContext(TitleContext);
  useEffect(() => {
    titleContext.setnowTitle(0);
    queryClient.clear();
  }, []);

  useEffect(() => {
    setName(userproContext.userPro?.name);
  }, [userproContext.userPro?.name]);

  return (
    <div>
      <Grid container spacing={2}>
        <Grid item xs={12} md={4} sm={12}>
          <LeftBar />
        </Grid>

        <Grid item xs={12} sm={12} md={8}>
          <RightBar />
          {/* {name != "里斯" && <Passage editor={true} params={{ name: name }} />} */}
        </Grid>
      </Grid>
    </div>
  );
}

const LeftBar = () => {
  const userproContext = useContext(UserProContext);
  const {
    data: tags,
    isFetching: tagFetching,
    isSuccess: tagSuccess,
  } = useQuery([GETTAGS_URL, { useToken: true }], getQueryFn);

  const {
    data: comment,
    isFetching: commentFetching,
    isSuccess: commentSuccess,
  } = useQuery([COMMENT_URL, { useToken: true }], getQueryFn);

  return (
    <div>
      {(tagFetching || commentFetching) && <Loading />}
      {tagSuccess && !tagFetching && commentSuccess && !commentFetching && (
        <Paper sx={{ width: "100%" }}>
          <Box className="leftProfile">
            <Avatar
              src={userproContext.userPro?.avatar}
              sx={{ width: 150, height: 150, marginBottom: "20px", mt: 1 }}
            ></Avatar>

            <Typography variant="h5">{userproContext.userPro?.name}</Typography>
          </Box>
          <Box
            sx={{
              marginTop: "30px",
              paddingLeft: "20px",
              paddingRight: "20px",
            }}
          >
            <Box
              sx={{
                flexDirection: "row",
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
              }}
            >
              <ListItemIcon>
                <ImportContactsIcon color="primary" sx={{ minWidth: "55px" }} />
              </ListItemIcon>
              <ListItemText>
                <Typography>
                  {"职称: " + userproContext.userPro?.title}
                </Typography>
              </ListItemText>
            </Box>{" "}
            <Box
              sx={{
                flexDirection: "row",
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
              }}
            >
              <ListItemIcon>
                <PersonIcon color="primary" sx={{ minWidth: "55px" }} />
              </ListItemIcon>
              <ListItemText>
                <Typography>
                  {"学位: " + userproContext.userPro?.degree}
                </Typography>
              </ListItemText>
            </Box>
            <Box
              sx={{
                flexDirection: "row",
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
              }}
            >
              <ListItemIcon>
                <SchoolIcon color="primary" sx={{ minWidth: "55px" }} />
              </ListItemIcon>
              <ListItemText>
                <Typography>
                  {"研究方向: " + userproContext.userPro?.research}
                </Typography>
              </ListItemText>
            </Box>{" "}
            <Box
              sx={{
                flexDirection: "row",
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
              }}
            >
              <ListItemIcon>
                <EmailIcon color="primary" sx={{ minWidth: "55px" }} />
              </ListItemIcon>
              <ListItemText>
                <Typography>
                  {"联系方式: " + userproContext.userPro?.email}
                </Typography>
              </ListItemText>
            </Box>
            <Box
              sx={{
                flexDirection: "row",
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
              }}
            >
              <ListItemIcon>
                <DomainIcon color="primary" sx={{ minWidth: "55px" }} />
              </ListItemIcon>
              <ListItemText>
                <Typography>
                  {"学院: " + userproContext.userPro?.college}
                </Typography>
              </ListItemText>
            </Box>
            <Box
              sx={{
                flexDirection: "row",
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
              }}
            >
              <ListItemIcon>
                <ClassIcon color="primary" sx={{ minWidth: "55px" }} />
              </ListItemIcon>
              <ListItemText>
                <Typography>
                  {"教授课程: " + userproContext.userPro?.lectureCourse}
                </Typography>
              </ListItemText>
            </Box>
            <Divider sx={{ margin: "15px 0" }} />
            <Box>
              <Typography variant="h6" sx={{ marginBottom: "10px" }}>
                科研项目
              </Typography>
              <Typography paragraph={true}>
                {userproContext.userPro?.introduction
                  ?.split("\n")
                  ?.map((value) => (
                    <Typography>{value}</Typography>
                  ))}
              </Typography>
            </Box>
            <Divider sx={{ margin: "15px 0" }} />
            <Box>
              <Typography variant="h6" sx={{ marginBottom: "10px" }}>
                教育背景
              </Typography>
              {/* <Typography paragraph={true}> */}
              {userproContext.userPro?.educationBackground
                ?.split("\n")
                ?.map((value) => (
                  <Typography>{value}</Typography>
                ))}
              {/* </Typography> */}
            </Box>
          </Box>
        </Paper>
      )}
    </div>
  );
};

const RightBar = () => {
  const [num1, setNum1] = useState(0);
  const [num2, setNum2] = useState(0);
  const [info1, setInfo1] = useState([]); //申请中的
  const [info2, setInfo2] = useState([]); //已完结的
  const [isFinished, setIsFinished] = useState();
  const navigate = useNavigate();
  const handleClick = (e) => {
    navigate("/teacher/homepage/notice/", {
      state: { isFinished: e.isFinished, info1: e.info1, info2: e.info2 },
    });
  };

  //获取课程的申请信息
  const {
    data: datac,
    isLoading: getLoading1,
    mutate: getMutate1,
    isSuccess: getSuccess1,
  } = useMutation(["getCourse"], mutateQueryFn);
  useEffect(() => {
    getMutate1({
      url: GET_COURSEAPPLICATION_URL,
      method: "get",
      useToken: true,
    });
  }, []);
  //获取考试的申请信息
  const {
    data: datae,
    isLoading: getLoading2,
    mutate: getMutate2,
    isSuccess: getSuccess2,
  } = useMutation(["getExams"], mutateQueryFn);

  useEffect(() => {
    getMutate2({ url: GET_EXAM_URL, method: "get", useToken: true });
  }, []);

  useEffect(() => {
    if (getSuccess1) {
      let num1F = num1;
      let num2F = num2;
      const info1F = info1;
      const info2F = info2;
      datac.data.data.map((val, key) => {
        if (val.status == 0) {
          num1F++;
          info1F.push({ ...val });
        } else {
          num2F++;
          info2F.push({ ...val });
        }
      });
      setNum1(num1F);
      setNum2(num2F);
      setInfo1(...[info1F]);
      setInfo2(...[info2F]);
    }
  }, [getSuccess1]);
  useEffect(() => {
    if (getSuccess2) {
      let num1F = num1;
      let num2F = num2;
      const info1F = info1;
      const info2F = info2;
      datae.data.data.map((val, key) => {
        if (val.status == 0) {
          num1F++;
          info1F.push({ ...val });
        } else {
          num2F++;
          info2F.push({ ...val });
        }
      });
      setNum1(num1F);
      setNum2(num2F);
      setInfo1(...[info1F]);
      setInfo2(...[info2F]);
    }
  }, [getSuccess2]);
  return (
    <>
      <Paper sx={{ width: "100%", height: 200 }}>
        <Box
          sx={{ display: "flex", flexDirection: "column", marginLeft: "37%" }}
        >
          <Typography
            variant="h6"
            sx={{ marginTop: 0, marginBottom: 1, paddingTop: 2, marginLeft: 8 }}
          >
            我的申请
          </Typography>
          <Box
            sx={{
              display: "flex",
              flexDirection: "row",
              justifyContent: "center",
              alignItems: "center",
            }}
          >
            <ListItemIcon>
              <FormatListBulletedIcon
                color="primary"
                sx={{ minWidth: "55px" }}
              ></FormatListBulletedIcon>
            </ListItemIcon>
            <ListItemText>
              <Typography variant="body1" gutterBottom>
                共有
                <Typography variant="h5" color="primary" component="span">
                  {num1}
                </Typography>
                项在申请中
              </Typography>
            </ListItemText>
          </Box>
          <Box
            sx={{
              display: "flex",
              flexDirection: "row",
              justifyContent: "center",
              alignItems: "center",
              marginLeft: 0,
            }}
          >
            <ListItemIcon>
              {/* <PlaylistAddCheckRoundedIcon color="primary" sx={{ minWidth: "55px" }}></PlaylistAddCheckRoundedIcon> */}
              <DoneIcon color="primary" sx={{ minWidth: "55px" }}></DoneIcon>
            </ListItemIcon>
            <ListItemText>
              <Typography variant="body1" gutterBottom>
                共有
                <Typography variant="h5" color="primary" component="span">
                  {num2}
                </Typography>
                项已办理结束
              </Typography>
            </ListItemText>
          </Box>
          <Button
            variant="contained"
            size="small"
            sx={{ mt: 1, marginBottom: 2, width: 140, marginLeft: 5 }}
            onClick={() =>
              handleClick({ isFinished: false, info1: info1, info2: info2 })
            }
          >
            点击查看
          </Button>
        </Box>
      </Paper>
    </>
  );
};
